<?php
require_once dirname(__FILE__).'/../Plugin.php';

class Plugin_Picture_Class extends My_Plugin
{
    public $upload;
    public $maxMB;
    public $minWidth;
    public $minHeight;
    public $maxWidth;
    public $maxHeight;
    public $allowedExtentions;
    public $pathToUpload;
    
    function  __construct($wertex)
    {
        parent::__construct('picture', $wertex);
        
        $this->upload = 'upload';
        $this->pathToUpload = parent::getPathToPlugin().$this->upload.DIRECTORY_SEPARATOR;
        $this->urlToUpload = parent::getUrlToPlugin().$this->upload.'/';
        
        $this->maxMB  = 2;
        $this->minWidth = 100;
        $this->minHeight = 100;
        $this->maxWidth = 1000;
        $this->maxHeight = 1000;
        $this->allowedExtentions = 'gif,jpg,png';
        $this->_initForm();
    }

    function action()
    {
        $post = $this->request->getPost();
        if ($this->request->isPost() AND $post[$this->getPrefix().'submit']) {
            if($this->add()){
                return true;
            }
        }
    }

    function getContent(){
        $row = $this->getLastRow();
        $img = getimagesize($this->pathToUpload.$row['picture']);
        return $this->toTemplate(array(
            'SRC' => $this->urlToUpload.$row['picture'],
            'TITLE' => $row['title'],
            'ALT' => $row['title'],
            'WIDTH' => $img[0],
            'HEIGHT' => $img[1],
        ), 'index');
    }

    function getHeader(){
        $row = $this->getLastRow();
        return $row['title'];
    }

    function add()
    {
        $values = $this->request->getPost();
        if ($this->form->isValid($values)) {
            $insertData = array();
            foreach ($this->getCols() AS $column) {
                $insertData[$column] = $values[$this->getPrefix().$column];
            }

            $extention = end(explode('.', $this->form->picture->getFileName()));
            $fileName = $this->getRandImgName($extention);
            $this->form->picture->addFilter(
                'Rename',
                array(
                    'target' => $this->pathToUpload.$fileName,
                    'overwrite' => true
                )
            );

            $this->form->picture->receive();

            $insertData['picture'] = $fileName;
            
            if($this->insert($insertData)){
                $this->setMessage('Veiksmīgi saglabāts');
                return $this->getLastId();
            }
        } else {
            $this->form->populate($values);
        }
    }

    /**
     * gets unique file name
     *
     * @param string(3) $extention
     * @return string
     */
    function getRandImgName($extention){
        $rows = array();
        $table = $this->getTable();
        
        while(1){
            $filename = rand(0, 9999999999).'.'.$extention;
            $result = $table->fetchAll(
                $table->select()->where('picture = ?', $filename)
            );
            if(!count($result->toArray()) AND !file_exists($this->pathToUpload.$filename)){
                break;
            }
        }
        return $filename;
    }

    function body()
    {
        $content = file_get_contents(dirname(__FILE__).'/template/form.html');
        $content = str_replace('{FORM}', $this->form, $content);
        return $content;
    }

    function _initForm()
    {
        $this->form = new Zend_Form;
        $this->form->addElement('hidden', $this->getPrefix().'wertex');
        $this->form->addElement('hidden', $this->getPrefix().'date');
        
        $title = new Zend_Form_Element_Text($this->getPrefix().'title', array(
            'label' => 'Title',
            'required' => false,
            'filters' => array(
                'StringTrim'
            ),
            'validators' => array(
                array('StringLength', false, array(0, 150))
            ),
        ));

        $picture = new Zend_Form_Element_File('picture',
            array(
                'label' => 'Picture '.$this->minWidth,
                'required' => true,
                'MaxFileSize' => $this->maxMB * 1048576, // 2097152 bytes = 2 megabytes
                'validators' => array(
                    array('Count', false, 1),
                    array('Size', false, $this->maxMB * 1048576),
                    array('Extension', false, $this->allowedExtentions),
                    array('ImageSize', false, array('minwidth' => $this->minWidth,
                                                    'minheight' => $this->minHeight,
                                                    'maxwidth' => $this->maxWidth,
                                                    'maxheight' => $this->maxHeight)
                    )
                )
            )
        );

        $picture->setValueDisabled(true);

        $submit = new Zend_Form_Element_Submit($this->getPrefix().'submit',
            array(
                'ignore'   => true,
                'label'    => 'Saglabāt',
            )
        );

        $this->form->addElements(array(
            $title,
            $picture,
            $submit
        ));

        $lastRow = $this->getLastRow();
        $this->form->setDefault($this->getPrefix().'title', $lastRow['title']);
        $this->form->setDefault($this->getPrefix().'picture', $lastRow['picture']);

        $this->form->setDefault($this->getPrefix().'wertex', $this->getWertex());
        $this->form->setDefault($this->getPrefix().'date', date("Y-m-d H:i:s"));
    }

}
